package com.cq.school.web;

import com.cq.school.config.Config;
import com.cq.school.entity.Apply;
import com.cq.school.entity.Article;
import com.cq.school.entity.School;
import com.cq.school.entity.Specialty;
import com.cq.school.service.ApplyService;
import com.cq.school.service.ArticleService;
import com.cq.school.service.SchoolService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: huke
 * Date: 13-11-28
 * Time: 下午10:28
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/man")
public class ManageAction {

    @Autowired
    private SchoolService schoolService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private Config config;

    private static Map<String,String> columnMap;
    static {
        columnMap = new HashMap<String, String>();
        columnMap.put("name","姓名");
        columnMap.put("schoolName","学校");
        columnMap.put("specialtyName","专业");
        columnMap.put("sex","性别");
        columnMap.put("age","年龄");
        columnMap.put("graduateSchool","毕业院校");
        columnMap.put("address","地址");
        columnMap.put("phone","电话");
        columnMap.put("mobile","手机");
        columnMap.put("qq","qq");
        columnMap.put("createTime","报名时间");
    }

    @RequestMapping(value = "/school/add",method = RequestMethod.GET)
    public String createSchool(Model model)
    {
        model.addAttribute("school", new School());
        return "manage/school_edit";
    }

    @RequestMapping(value = "/school/update/{id}",method = RequestMethod.GET)
    public String updateSchool(@PathVariable("id") Long id, Model model)
    {
        model.addAttribute("school",schoolService.getSchool(id));
        return "manage/school_edit";
    }

    @RequestMapping(value = "/school/save",method = RequestMethod.POST)
    public String saveSchool(School school)
    {
        schoolService.saveSchool(school);
        return "redirect:/man/school/list";
    }
    @RequestMapping(value = "/school/delete/{id}")
    public String deleteSchool(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        schoolService.deleteSchool(id);
        redirectAttributes.addFlashAttribute("message", "删除任务成功");
        return "redirect:/man/school/list";
    }


    @RequestMapping(value = "/school/list",method = RequestMethod.GET)
    public String listSchool(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                             @RequestParam(value = "page.size", defaultValue = "10") int pageSize,
                             Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");

        Page<School> list = schoolService.listSchool(searchParams,pageNumber,pageSize);
        model.addAttribute("list", list);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "manage/school_list";
    }


    @RequestMapping(value = "/article/add",method = RequestMethod.GET)
    public String createArticle(Model model)
    {
        model.addAttribute("article",new Article());
        model.addAttribute("categorys",config.getArticleCategory());
        model.addAttribute("schools",schoolService.listSchool());
        return "manage/article_edit";
    }

    @RequestMapping(value = "/article/update/{id}",method = RequestMethod.GET)
    public String updateArticle(@PathVariable("id") Long id, Model model)
    {
        model.addAttribute("article",articleService.getArticle(id));
        model.addAttribute("categorys",config.getArticleCategory());
        model.addAttribute("schools",schoolService.listSchool());
        return "manage/article_edit";
    }

    @RequestMapping(value = "/article/save",method = RequestMethod.POST)
    public String saveArticle(Article article)
    {
        articleService.saveArticle(article);
        return "redirect:/man/article/list";
    }

    @RequestMapping(value = "/article/delete/{id}")
    public String deleteArticle(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        articleService.deleteArticle(id);
        redirectAttributes.addFlashAttribute("message", "删除文章成功");
        return "redirect:/man/article/list";
    }

    @RequestMapping(value = "/article/list",method = RequestMethod.GET)
    public String listArticle(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                              @RequestParam(value = "page.size", defaultValue = "10") int pageSize,
                              @RequestParam(value = "category", defaultValue = "0") int category,
                              Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");

        Page<Article> list = articleService.listArticle(category,searchParams,pageNumber,pageSize);

        model.addAttribute("list", list);
        model.addAttribute("category",category);
        model.addAttribute("categorys",config.getArticleCategory());
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "manage/article_list";
    }

    @RequestMapping(value = "/apply/list",method = RequestMethod.GET)
    public String listApply(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                            @RequestParam(value = "page.size", defaultValue = "10") int pageSize,
                            @RequestParam(value = "schoolId", defaultValue = "0") long schoolId,
                            Model model, ServletRequest request) {

        Page<Apply> list = applyService.listApply(schoolId,pageNumber,pageSize);
        model.addAttribute("schools",schoolService.listSchool());
        model.addAttribute("list", list);
        model.addAttribute("schoolId", schoolId);
        model.addAttribute("specialtiyMap",schoolService.getSpecialtiyMap());
        return "manage/apply_list";
    }

    @RequestMapping(value = "/apply/export",method = RequestMethod.GET)
    public void exportApply(
            @RequestParam(value = "schoolId", defaultValue = "0") long schoolId,
            Model model, ServletRequest request,HttpServletResponse response) {
        List<Apply> list = applyService.listApply(schoolId);
        Map<Long,String> map = schoolService.getSpecialtiyMap();
        for(Apply apply:list)
            apply.setSpecialtyName(map.get(apply.getSpecialty()));
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("报名表");
        //workbook.setSheetName(0,sheetName,HSSFWorkbook..ENCODING_UTF_16);
        HSSFRow row= sheet.createRow((short)0);
        HSSFCell cell = null;

        int nColumn=columnMap.keySet().size();


        //写入各个字段的名称
        int iCell=0;
        for(Iterator it=columnMap.keySet().iterator();it.hasNext();) {
            cell = row.createCell(iCell++);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(columnMap.get(it.next()));
        }

        int iRow=1;
        //写入各条记录，每条记录对应Excel中的一行
        for(Apply apply:list)    {
            row= sheet.createRow((short)iRow);
            iCell=0;
            for(Iterator<String> it=columnMap.keySet().iterator();it.hasNext();) {
                cell = row.createCell(iCell++);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                String pName = it.next();
                String value = "";
                if(pName.equals("createTime"))
                    value = DateFormatUtils.format(apply.getCreateTime(),"yyyy-MM-dd HH:ss:mm");
                else
                    try {
                        value = BeanUtils.getProperty(apply,pName);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                cell.setCellValue(value);
            }
            iRow++;
        }
        String filename = "报名.xls";//设置下载时客户端Excel的名称
        response.setContentType("application/vnd.ms-excel");
        try {
            response.addHeader("Content-Disposition", "filename=\"" + URLEncoder.encode(filename, "utf-8") + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/school/recommend")
    public String recommend(@RequestParam("id") Long id,@RequestParam("recomm") int recommend,@RequestParam("type") int type, RedirectAttributes redirectAttributes,HttpServletRequest request) {
        if(id!=null&&id>0)
            schoolService.updateRecommend(id,recommend,type);
        redirectAttributes.addFlashAttribute("message", "更新推荐成功");
        return "redirect:"+request.getHeader("referer");
    }
    @RequestMapping(value = "/school/specialty/list")
    public String listSpecialty(@RequestParam("schoolId") long schoolId,Model model)
    {
        model.addAttribute("schoolId",schoolId);
        model.addAttribute("list",schoolService.findSpecialtyBySchoolId(schoolId));
        return "manage/specialty_list";
    }

    @RequestMapping(value = "/school/specialty/update")
    @ResponseBody
    public Specialty updateSpecialty(Specialty specialty)
    {
        return schoolService.saveSpecialty(specialty);
    }

    @RequestMapping(value = "/school/specialty/delete")
    @ResponseBody
    public String deleteSpecialty(@RequestParam("id") long id)
    {
        schoolService.deleteSpecialty(id);
        return "1";
    }
    @RequestMapping(value = "/school/pictures/list")
    public String listPictures(@RequestParam("schoolId") long schoolId,Model model){
        model.addAttribute("list",schoolService.listPictures(schoolId));
        model.addAttribute("schoolId",schoolId);
        return "/manage/school_pictures";
    }

    @RequestMapping(value = "/school/pictures/delete")
    @ResponseBody
    public String listPictures(@RequestParam("id") long id){
        schoolService.deleteSchoolPicture(id);
        return "1";
    }

}
